package logic

import (
	"context"

	"mail/service/account/rpc/accountclient"
	"mail/service/outlay/model"
	"mail/service/outlay/rpc/internal/svc"
	"mail/service/outlay/rpc/outlay"
	"mail/service/receipt/rpc/receiptclient"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

type EntrantLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEntrantLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EntrantLogic {
	return &EntrantLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *EntrantLogic) Entrant(in *outlay.EntrantRequest) (*outlay.EntrantResponse, error) {
	// todo: add your logic here and delete this line
	_, err := l.svcCtx.AccountRpc.Particular(l.ctx, &accountclient.ParticularRequest{
		Id: in.Uid,
	})
	if err != nil {
		return nil, err
	}
	_, err = l.svcCtx.ReceiptRpc.Scenery(l.ctx, &receiptclient.SceneryRequest{
		Id: in.Rid,
	})
	if err != nil {
		return nil, err
	}
	//whether finish rent of outlay.
	_, err = l.svcCtx.OutlayModel.FindOneByRid(in.Rid)
	if err == nil {
		return nil, status.Error(100, "outlay is finish.")
	}
	//初学者、实习生
	apprentice := model.Outlay{
		Uid:    in.Uid,
		Rid:    in.Rid,
		Amount: in.Amount,
		Source: 0,
		Status: 0,
	}
	//沉思的、体贴的
	thoughtful, err := l.svcCtx.OutlayModel.Insert(l.ctx, &apprentice)
	if err != nil {
		return nil, status.Error(500, err.Error())
	}
	apprentice.Id, err = thoughtful.LastInsertId()
	if err != nil {
		return nil, status.Error(500, err.Error())
	}

	return &outlay.EntrantResponse{
		Id: apprentice.Id,
	}, nil
}
